<template>
   <div class="app-container">
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            <!-- <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:menu:add']">新增</el-button> -->
         </el-col>
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :search="false"></right-toolbar>
      </el-row>

      <el-table v-if="refreshTable" v-loading="loading" stripe border :data="menuList" row-key="id"
         :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
         <el-table-column prop="meta.title" label="菜单名称" :show-overflow-tooltip="true" :min-width="400"></el-table-column>
         <el-table-column prop="sort" label="排序" :min-width="100"></el-table-column>
         <el-table-column prop="perm" label="权限标识" :min-width="160" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column prop="component" label="组件路径" :min-width="240" :show-overflow-tooltip="true"></el-table-column>
         <!-- <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
         </el-table-column> -->
         <el-table-column label="创建时间" :min-width="200" prop="createdTime">
         </el-table-column>
         <el-table-column label="操作" :min-width="140" class-name="small-padding fixed-width">
            <template #default="scope">
               <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:menu:edit']">修改</el-button>
               <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                  v-hasPermi="['system:menu:add']">新增</el-button>
               <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:menu:remove']">删除</el-button> -->
               <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button link type="primary" @click="handleAdd(scope.row)">新增</el-button>
               <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="title" v-model="open" width="680px" append-to-body align-center :close-on-click-modal="false">
         <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
               <el-col :span="24">
                  <el-form-item label="上级菜单">
                     <el-tree-select v-model="form.parentId" :data="menuOptions"
                        :props="{ value: 'id', label: (data) => data.meta.title, children: 'children' }" value-key="id" :disabled="title === '修改菜单'"
                        placeholder="选择上级菜单" check-strictly >
                     </el-tree-select>
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="菜单类型" prop="type">
                     <el-radio-group v-model="form.type">
                        <el-radio :value="1">目录</el-radio>
                        <el-radio :value="2">菜单</el-radio>
                        <el-radio :value="3">按钮</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="sort">
                     <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="菜单名称" prop="meta.title">
                     <el-input v-model="form.meta.title" placeholder="请输入菜单名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="12" v-if="form.type !== 3">
                  <el-form-item prop="path">
                     <template #label>
                        <span>
                           <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           路由地址
                        </span>
                     </template>
                     <el-input v-model="form.path" :formatter="(value) => value.replace(/\//g, '')" placeholder="请输入路由地址" />
                  </el-form-item>
               </el-col>
               <el-col :span="12" v-if="form.type === 2">
                  <el-form-item prop="component">
                     <template #label>
                        <span>
                           <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           组件路径
                        </span>
                     </template>
                     <el-input v-model="form.component" placeholder="请输入组件路径" />
                  </el-form-item>
               </el-col>
               <el-col :span="12" v-if="form.type === 3">
                  <el-form-item>
                     <el-input v-model="form.perm" placeholder="请输入权限标识" maxlength="100" />
                     <template #label>
                        <span>
                           <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                              placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           权限字符
                        </span>
                     </template>
                  </el-form-item>
               </el-col>
               <el-col :span="12" v-if="form.type === 2">
                  <el-form-item>
                     <el-input v-model="form.params" placeholder="请输入路由参数" maxlength="255" />
                     <template #label>
                        <span>
                           <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           路由参数
                        </span>
                     </template>
                  </el-form-item>
               </el-col>
               <el-col :span="12" v-if="form.type !== 3">
                  <el-form-item>
                     <template #label>
                        <span>
                           <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           显示状态
                        </span>
                     </template>
                     <el-radio-group v-model="form.hidden">
                        <el-radio v-for="dict in sys_show_hide" :key="dict.value" :value="dict.value">{{ dict.label
                           }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">取 消</el-button>
               <el-button type="primary" @click="submitForm" :loading="addLoading || editLoading">确 定</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu" lang="ts">
import { createMenuReq, deleteListReq, menuListReq, updateListReq } from "@/api/system/menu/index";

const { proxy } = getCurrentInstance();
const sys_show_hide = [
   {
      value: false,
      label: '显示'
   },
   {
      value: true,
      label: '隐藏'
   },
]

const menuList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
const form = ref({
   id: undefined,
   parentId: '0',
   meta: {
      title: undefined,
   },
   component: undefined,
   params: undefined,
   path: undefined,
   type: 1,
   hidden: false,
   sort: undefined,
   perm: undefined
})
const rules =  ref({
   "meta.title": [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
   sort: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
   path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }]
})

const menuOptions = computed(() => {
   const menu = {
      id: '0',
      meta: {
         title: "主类目"
      },
      children: [] 
   };
   menu.children = JSON.parse(JSON.stringify(menuList.value))
   return [menu]
})

const { runAsync: getList, loading } = useRequest(menuListReq, {
   manual: true,
   onSuccess: (res) => {
      menuList.value = res
   }
})


const { run: addMenu, loading: addLoading } = useRequest(createMenuReq, {
   manual: true,
   onSuccess: () => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
   }
})

const { run: updateMenu, loading: editLoading } = useRequest(updateListReq, {
   manual: true,
   onSuccess: () => {
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
   }
})

const { runAsync: delMenu } = useRequest(deleteListReq, {
   manual: true,
})

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      parentId: '0',
      meta: {
         title: undefined,
      },
      component: undefined,
      params: undefined,
      path: undefined,
      type: 1,
      hidden: false,
      sort: undefined,
      perm: undefined
      // isFrame: "1",
      // isCache: "0",
      // status: "0"
   };
   proxy.resetForm("menuRef");
}

/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   if (row != null && row.id) {
      form.value.parentId = row.id;
   } else {
      form.value.parentId = '0';
   }
   open.value = true;
   title.value = "添加菜单";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
   refreshTable.value = false;
   isExpandAll.value = !isExpandAll.value;
   nextTick(() => {
      refreshTable.value = true;
   });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   form.value = {
      id: row?.id,
      parentId: row?.parentId,
      meta: {
         title: row?.meta?.title,
      },
      component: row?.component,
      path: row?.path,
      params: row?.params,
      type: row?.type,
      hidden: row?.hidden,
      sort: row?.sort,
      perm: row?.perm
   };
   open.value = true;
   title.value = "修改菜单";
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["menuRef"].validate(valid => {
      if (valid) {
         const { type, path, parentId } = form.value
         const params = {
            ...form.value,
            name: type === 3 ? undefined : path?.replace(/\//g, '').replace(/\b\w/g, (match) => match.toUpperCase()), // 组件名称大写开头
            path: type===3 ? undefined : ([1].includes(type) && parentId === '0' && !path.includes('/') ) ? `/${path}` : path // 根目录需要加/
         }
         if (params.id != undefined) {
            updateMenu(params)
         } else {
            addMenu(params)
         }
      }
   });
}

/** 删除按钮操作 */
function handleDelete(row) {
   ElMessageBox.confirm('是否确认删除名称为"' + row.meta.title + '"的数据项?',
      "",
      {
         type: 'warning',
         confirmButtonClass: 'el-button--danger',
         confirmButtonText: '删除',
         closeOnClickModal: false,
         'show-close': false,
      }
   ).then(function () {
      return delMenu({id: row.id});
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

getList();
</script>
